package com.tarena.lbs.activity.service.impl;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.business.api.BusinessApi;
import com.tarena.lbs.business.api.pojo.BusinessDto;
import com.tarena.lbs.common.enums.BusinessTypeEnum;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tarena.lbs.common.enums.Roles;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;
    @Value("${url.prefix}")
    private String urlPrefix;

    @Override
    public PageResult<ActivityVO> pageList(ActivityQuery query) {
        //验证用户
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null){
            throw new IllegalArgumentException("用户未登录");
        }
        //判断用户角色是否为商家
        if (userPrinciple.getRole() != Roles.SHOP){
            throw new IllegalArgumentException("用户不是商家");
        }
        //查询商家信息-是否存在
        AdminDto adminDto = userApi.getAdminById(userPrinciple.getId());
        if(adminDto.getBusinessId() == null){
            throw new IllegalArgumentException("商家未绑定店铺");
        }
        //设置商家ID
        query.setBusinessId(adminDto.getBusinessId());
        log.debug("活动分页查询，入参:{}",query);
        // 分页查询活动列表
        PageResult<ActivityVO> pageResult = new PageResult<>();
        PageInfo<ActivityPO> pageInfo = activityRepository.pagesList(query);
        log.debug("活动分页查询，出参:{}",pageInfo);
        pageResult.setPageNo(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotal(pageInfo.getTotal());
        List<ActivityVO> vos = null;
        // 从分页信息中获取管理员持久化对象列表
        List<ActivityPO> pos = pageInfo.getList();
        // 判断持久化对象列表是否不为空
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                ActivityVO vo = new ActivityVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        // 设置分页结果中的数据列表
        pageResult.setObjects(vos);
        return pageResult;
    }

    @Override
    public void add(ActivityAddParam param) {
        log.debug("活动保存，入参:{}",param);
        //验证用户
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null){
            throw new IllegalArgumentException("用户未登录");
        }
        //判断用户角色是否为商家
        if (userPrinciple.getRole() != Roles.SHOP){
            throw new IllegalArgumentException("用户不是商家");
        }
        //查询商家信息-是否存在
        AdminDto adminDto = userApi.getAdminById(userPrinciple.getId());
        if(adminDto.getBusinessId() == null){
            throw new IllegalArgumentException("用户未绑定商家");
        }


        //设置商家ID
        param.setBusinessId(adminDto.getBusinessId());
        //保存活动
        ActivityPO activityPO = new ActivityPO();
        log.debug("param:{}",param);
        BeanUtils.copyProperties(param,activityPO);
        String start = param.getStartDate();
        String end = param.getEndDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(start);
            Date endDate = sdf.parse(end);
            activityPO.setStartDate(startDate);
            activityPO.setEndDate(endDate);
        }catch (ParseException e){
            e.printStackTrace();
        }

        activityPO.setStatus(0);
        activityPO.setEnableStatus(0);
        log.debug("activityPO:{}",activityPO);
        activityPO.setCreateAt(new Date());
        activityRepository.add(activityPO);
        //通过附件保存活动图片
        List<PicUpdateParam> picParams = new ArrayList<>();
        String imgIds = param.getImgIds();
        List<Integer> imgIdList = Arrays.stream(imgIds.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        //封装图片更新参数
        imgIdList.forEach(imgId->{
            PicUpdateParam picParam = new PicUpdateParam();
            picParam.setId(imgId);
            picParam.setBusinessType(BusinessTypeEnum.ACTIVITY.getType());
            picParam.setBusinessId(activityPO.getId());
            log.debug("封装信息picParam:{}",picParam);
            picParams.add(picParam);
        });
        attachApi.batchUpdateBusiness(picParams);
    }

    @Override
    public ActivityVO detail(Integer id) {
        ActivityVO activityVO = new ActivityVO();
        ActivityPO activityPO = activityRepository.findById(id);
        if (activityPO == null){
            throw new IllegalArgumentException("活动不存在");
        }
        BeanUtils.copyProperties(activityPO,activityVO);

        //查询活动图片uuid列表
        AttachQuery query = new AttachQuery();
        query.setBusinessType(BusinessTypeEnum.ACTIVITY.getType());
        query.setBusinessId(activityPO.getId());
        List<AttachDTO> attachDTOS = attachApi.getAttachInfo(query);
        List<String> uuids = attachDTOS.stream().map(AttachDTO::getFileUuid).collect(Collectors.toList());
        //封装活动图片地址
        List<String> imgUrls = uuids.stream().map(uuid->urlPrefix+uuid).collect(Collectors.toList());
        activityVO.setImgPics(imgUrls);
        log.debug("活动详情activityVO:{}",activityVO);
        return activityVO;
    }
}
